import {Button, message, Modal, Tag} from "antd";
import {useEffect, useState} from "react";
import {CloseOutlined} from "@ant-design/icons";
import RoleList from "../role/roleList";
import RequestUtils from "../../../utils/requestUtils";
import RequestApis from "../../../apis/requestApis";

/**
 * 为用户分配角色模态框组件
 */
const UserRoleAllocate = (props) => {
    const {
        editUserModalVisible,
        setEditUserModalVisible,
        userId,
        roles,
        searchUserById
    } = props;

    const [messageApi, contextHolder] = message.useMessage();
    // 要分配的角色列表（基于roleName去重）
    const [allocateRoles, setAllocateRoles] = useState([]);
    // 角色列表模态框
    const [roleListModalVisible, setRoleListModalVisible] = useState(false);

    // 初始化/刷新角色列表（基于roleName去重）
    useEffect(() => {
        if (editUserModalVisible.allocateUserRole && roles) {
            const uniqueRoles = Array.from(new Map(roles.map(role => [role.roleName, role])).values());
            setAllocateRoles(uniqueRoles);
        }
    }, [editUserModalVisible.allocateUserRole, roles]);

    // 删除角色（基于roleName删除）
    const removeRole = (roleName) => {
        setAllocateRoles(allocateRoles.filter(role => role.roleName !== roleName));
    };

    /**
     * 为用户分配角色
     */
    const doAllocateUserRole = () => {
        RequestUtils.post(RequestApis.permissionManage.allocateUserRole, {
            userId: userId,
            roleIds: allocateRoles.map(role => role.roleId)
        }).then(res => {
            searchUserById();
            messageApi.success("为用户分配角色成功");
            setEditUserModalVisible({
                ...editUserModalVisible,
                allocateUserRole: false
            });
        }).catch(err => messageApi.error(err.message))
    }

    return (
        <Modal
            open={editUserModalVisible.allocateUserRole}
            title="为用户分配角色"
            width={600}
            onCancel={() => setEditUserModalVisible({
                ...editUserModalVisible,
                allocateUserRole: false
            })}
            footer={
                <div style={{display: 'flex', justifyContent: 'flex-end', gap: 12, padding: '12px 0 8px'}}>
                    <Button
                        type={"primary"}
                        size="middle"
                        style={{
                            borderRadius: 6,
                            padding: '6px 24px',
                            fontSize: 13,
                            transition: 'all 0.2s ease'
                        }}
                        onClick={() => doAllocateUserRole()}
                    >
                        保存
                    </Button>
                    <Button
                        danger
                        size="middle"
                        style={{
                            borderRadius: 6,
                            padding: '6px 24px',
                            fontSize: 13,
                            transition: 'all 0.2s ease'
                        }}
                        onClick={() => setEditUserModalVisible({
                            ...editUserModalVisible,
                            allocateUserRole: false
                        })}
                    >
                        取消
                    </Button>
                </div>
            }
            style={{
                borderRadius: 12,
                overflow: 'hidden',
                boxShadow: '0 4px 20px rgba(0, 0, 0, 0.15)',
                padding: 12,
                borderTopLeftRadius: 0,
                borderTopRightRadius: 0
            }}
            titleStyle={{
                fontSize: 18,
                fontWeight: 600,
                color: '#1f2329',
                padding: 20,
                borderBottom: '1px solid #f0f0f0'
            }}
            maskClosable={false}
        >
            <div style={{marginTop: 8}}>
                {contextHolder}

                {/* 打开角色列表按钮 */}
                <div>
                    <Button
                        color={'purple'}
                        variant={'outlined'}
                        size="middle"
                        style={{
                            height: 36,
                            width: 220,
                            borderRadius: 6,
                            borderColor: '#722ed1',
                            color: '#722ed1',
                            fontSize: 13,
                            transition: 'all 0.2s ease',
                            '&:hover': {
                                backgroundColor: '#f5f0ff',
                                borderColor: '#8a4fff'
                            }
                        }}
                        onClick={() => setRoleListModalVisible(true)}
                    >
                        打开角色列表
                    </Button>
                </div>

                {/* 已关联角色标题 */}
                <div style={{
                    color: '#4E5969',
                    marginTop: 24,
                    fontSize: 14,
                    fontWeight: 500,
                    display: 'flex',
                    alignItems: 'center',
                    gap: 8
                }}>
                    <div style={{
                        width: 4,
                        height: 16,
                        backgroundColor: '#722ed1',
                        borderRadius: 2
                    }} />
                    当前用户已关联的角色
                </div>

                {/* 角色标签容器 */}
                <div style={{
                    background: '#ffffff',
                    marginTop: 12,
                    padding: 16,
                    borderRadius: 8,
                    minHeight: 80,
                    display: 'flex',
                    alignItems: 'flex-start',
                    flexWrap: 'wrap',
                    border: '1px solid #f0f0f0',
                    boxShadow: '0 1px 3px rgba(0, 0, 0, 0.05)'
                }}>
                    {allocateRoles && allocateRoles.length > 0 ?
                        allocateRoles.map(v => (
                            <Tag
                                color='geekblue'
                                style={{
                                    margin: '0 8px 8px 0',
                                    padding: '5px 12px',
                                    borderRadius: 6,
                                    fontSize: 13,
                                    height: 32,
                                    display: 'inline-flex',
                                    alignItems: 'center',
                                    gap: 6,
                                    transition: 'all 0.2s ease',
                                    '&:hover': {
                                        transform: 'translateY(-1px)',
                                        boxShadow: '0 2px 5px rgba(24, 144, 255, 0.15)'
                                    }
                                }}
                                key={v.roleName}
                            >
                                <span>{v.roleName}</span>
                                <span
                                    style={{
                                        fontSize: 12,
                                        cursor: 'pointer',
                                        width: 16,
                                        height: 16,
                                        borderRadius: 50,
                                        display: 'inline-flex',
                                        alignItems: 'center',
                                        justifyContent: 'center',
                                        '&:hover': {
                                            backgroundColor: 'rgba(255, 255, 255, 0.3)'
                                        }
                                    }}
                                    onClick={(e) => {
                                        e.stopPropagation();
                                        removeRole(v.roleName);
                                    }}
                                >
                                    <CloseOutlined />
                                </span>
                            </Tag>
                        )) : (
                            <div style={{
                                width: '100%',
                                padding: 16,
                                textAlign: 'center',
                                fontSize: 13,
                                color: '#9ca3af',
                                backgroundColor: '#f9fafb',
                                borderRadius: 6,
                                border: '1px dashed #e5e7eb'
                            }}>
                                当前无任何角色
                            </div>
                        )
                    }
                </div>
            </div>

            {/* 角色查询模态框 */}
            <RoleList
                roleListModalVisible={roleListModalVisible}
                setRoleListModalVisible={setRoleListModalVisible}
                allocateRoles={allocateRoles}
                setAllocateRoles={setAllocateRoles}
            />
        </Modal>
    );
};

export default UserRoleAllocate;